package com.zsy.springframework.beans.facotry.strategy;

import com.zsy.springframework.beans.facotry.config.BeanDefinition;
import com.zsy.springframework.beans.facotry.exception.BeansException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class SimpleInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiation(BeanDefinition beanDefinition, String beanName, Constructor useConstructor, Object[] args) {
        Class clazz = beanDefinition.getBeanClass();
        try {
            if (useConstructor != null) {
                return clazz.getDeclaredConstructor().newInstance();
            } else {
                return clazz.getDeclaredConstructor(useConstructor.getParameterTypes()).newInstance(args);
            }
        } catch (InvocationTargetException | NoSuchMethodException | InstantiationException | IllegalAccessException e) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
        }
    }
}
